package com.dyz.leetcode._13_binaryTree;

import com.dyz.leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class _101_isSymmetric {

    //DFS
    public boolean isSymmetric(TreeNode root) {
        if(root==null){return true;}

        return isMirror(root.left, root.right);

    }

    private boolean isMirror(TreeNode t1, TreeNode t2){
        if(t1==null && t2==null){return true;}
        if(t1==null || t2==null){return false;}
        if(t1.val!=t2.val){return false;}

        return isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left);
    }

    //BFS
    private boolean isSymmetric1(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        }
        Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
        Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
        queue1.offer(p);
        queue2.offer(q);
        while (!queue1.isEmpty() && !queue2.isEmpty()) {
            TreeNode node1 = queue1.poll();
            TreeNode node2 = queue2.poll();
            if (node1.val != node2.val) {
                return false;
            }
            TreeNode left1 = node1.left, right1 = node1.right;
            TreeNode left2 = node2.left, right2 = node2.right;
            if (left1 == null ^ right2 == null) {
                return false;
            }
            if (right1 == null ^ left2 == null) {
                return false;
            }
            if (left1 != null) {
                queue1.offer(left1);
            }
            if (right2 != null) {
                queue2.offer(right2);
            }

            if (left2 != null) {
                queue2.offer(left2);
            }
            if (right1 != null) {
                queue1.offer(right1);
            }
        }
        return queue1.isEmpty() && queue2.isEmpty();
    }
}
